<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\model\User;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 班级管理
 *
 * @icon fa fa-circle-o
 */
class SchoolClass extends Backend
{

    /**
     * SchoolClass模型对象
     * @var \app\admin\model\SchoolClass
     */
    protected $model = null;
    protected $dataLimit = 'auth';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\SchoolClass;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("isleaveList", $this->model->geisleaveList());
        $this->view->assign("classdiscountList", $this->model->geclassdiscountList());
        $this->assignconfig('cost', $this->auth->check('school_class/cost'));
        $this->assignconfig('school_class_subject_schedule', $this->auth->check('school_class_subject_schedule/index'));
        $this->assignconfig('school_calss_user', $this->auth->check('school_calss_user/index'));
        $this->assignconfig('remarks', $this->auth->check('school_class/remarks'));
        $this->assignconfig('translate', $this->auth->check('school_class/translate'));

    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['admin', 'schoolclasstype', 'schoolclasssubject'])
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['admin', 'schoolclasstype', 'schoolclasssubject'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            // print_r( $this->model->getLastSql());
            foreach ($list as $k => $row) {
                $row->number = db('school_calss_user')->where('status', '0')->where('class_id', $row->id)->count();
                $row->visible(['id', 'class_name', 'class_type', 'number', 'renew', 'remind', 'start_time', 'status', 'end_time', 'createtime', 'remarks']);
                $row->visible(['admin']);
                $row->getRelation('admin')->visible(['nickname']);
                $row->visible(['schoolclasstype']);
                $row->getRelation('schoolclasstype')->visible(['name']);
                $row->visible(['schoolclasssubject']);
                $row->schoolclasssubject->subject_name = $row->schoolclasssubject->schoolsubject['subject_name'];
                $row->schoolclasssubject->cost = $row->schoolclasssubject->schoolsubject['cost'] * $row->schoolclasssubject->total_class_hour;
                $row->schoolclasssubject->use_class_hour = $row->schoolclasssubject->total_class_hour - $row->schoolclasssubject->use_class_hour;
                $row->getRelation('schoolclasssubject')->visible(['id', 'total_class_hour', 'use_class_hour', 'subject_name', 'cost']);
                // print_r($row->schoolclasssubject->schoolsubject['subject_name']);

            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加班级
     * @return string
     * @throws Exception
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    $data_subject = [
                        'subject_id' => $params['subject_id'],
                        'total_class_hour' => $params['total_class_hour'],
                    ];
                    unset($params['subject_id']);
                    unset($params['total_class_hour']);
                    $params['start_time'] = strtotime($params['start_time']);
                    $params['createtime'] = time();
                    $class_id = Db::name('school_class')->insertGetId($params);
                    $data_subject['class_id'] = $class_id;
                    $result = Db::name('school_class_subject')->insert($data_subject);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }


    /**
     * @param null $ids
     * @return string
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->alias('a')
            ->field('a.*,b.subject_id,b.total_class_hour')
            ->join('ed_school_class_subject b', 'b.class_id = a.id')
            ->where('a.id', $ids)
            ->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    $data_subject = [
                        'subject_id' => $params['subject_id'],
                        'total_class_hour' => $params['total_class_hour'],
                    ];
                    unset($params['subject_id']);
                    unset($params['total_class_hour']);
                    $params['start_time'] = strtotime($params['start_time']);

                      Db::name('school_class_subject_schedule')->where('class_id', $ids)->update(['csmmeet_room_id' =>$params['csmmeet_room_id']]);
                    Db::name('school_class')->where('id', $ids)->update($params);
                    $result = Db::name('school_class_subject')->where('class_id', $ids)->update($data_subject);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function remarks()
    {
        $id = input('ids');
        $data = [
            'remarks' => $this->request->request('remarks')
        ];
        $this->model->where('id', $id)->update($data);
        $this->success();
    }

    /**
     * 毕业
     */
    public function translate()
    {
        $class_id = input('ids');
        $class_info = $this->model->where('id', $class_id)->find();
        if ($class_info['status'] != '0') {
            $this->error('状态错误');
        }
        $calss_user_list = db('school_calss_user')
            ->where('status', '0')
            ->where('class_id', $class_info['id'])
            ->select();
        try {
            Db::startTrans();
            db('school_class')->where('id', $class_info['id'])->update(['status' => '1']);
            $dataLog = [];
            foreach ($calss_user_list as $v) {
                db('school_calss_user')->where('id', $v['id'])->update(['status' => '1', 'work_time' => time()]);
                if ($v['total_class_hour'] - $v['use_class_hour'] > 0) {
                    if ($v['class_discount'] == 1) {
                        $money = $v['cost'] / $v['total_class_hour'] * ($v['total_class_hour'] - $v['use_class_hour']);
                    } else if ($v['class_discount'] == 3) {
                        if ($v['use_class_hour'] < $v['quan']) {
                            $shengyu = $v['quan'] - $v['use_class_hour'];
                            db('user')->where('id', $v['user_id'])->setInc('discount_amount', $shengyu);
                            $dataLoss = [
                                'admin_id' => $this->auth->id,
                                'user_id' => $v['user_id'],
                                'create_time' => time(),
                                'content' => '退班，退回费用优惠课时' . $shengyu,
                            ];
                            db('SchoolUserLog')->insert($dataLoss);
                            $money = $v['cost'] * ($v['total_class_hour'] - $v['use_class_hour'] - $shengyu);
                        }else{
                            $money = $v['cost'] * ($v['total_class_hour'] - $v['use_class_hour']);
                        }
                    }else  if ($v['class_discount'] == 1) {
                        $money = ($v['total_class_hour'] - $v['use_class_hour']) * $v['cost'];
                    }

                    $common_user = new User();
                    $common_user->money($money, $v['user_id'], '毕业');
                    db('user')->where('id', $v['user_id'])->update(['admin_id' => '']);
                    $dataLog[] = [
                        'admin_id' => $this->auth->id,
                        'user_id' => $v['user_id'],
                        'create_time' => time(),
                        'content' => $class_info['class_name'] . '毕业，退回费用' . $money . '元'
                    ];
                } else {
                    $dataLog[] = [
                        'admin_id' => $this->auth->id,
                        'user_id' => $v['user_id'],
                        'create_time' => time(),
                        'content' => $class_info['class_name'] . '毕业成功'
                    ];
                }
            }
            db('SchoolUserLog')->insertAll($dataLog);
            Db::commit();
            $this->success('毕业成功');
        } catch (Exception $e) {
            $this->error($e->getMessage() .'行数'. $e->getLine());
            Db::rollback();
        }


    }
}
